package server.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import server.common.R;
import server.dao.UserMapper;
import server.entity.User;
import server.service.UserService;
import server.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl implements UserService {

    private SqlSession session;
    @Override
    public R<User> login(String username, String password) {
        try {
            if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
                return R.error("账号或密码为空！");
            }
            password = SecureUtil.md5(password);//密码md5加密存储对比
            session=SqlSessionUtil.getSession();
            UserMapper mapper = session.getMapper(UserMapper.class);
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername,username);
            User user = mapper.selectOne(queryWrapper);
            if(user==null){
                return R.error("不存在该账号！");
            }
            if(!user.getPassword().equals(password)){
                return R.error("密码错误！");
            }
            return R.success(user);
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<User> register(String username, String password) {
        try {
            if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
                return R.error("账号或密码为空！");
            }
            password = SecureUtil.md5(password);//密码md5加密存储
            session=SqlSessionUtil.getSession();
            UserMapper mapper = session.getMapper(UserMapper.class);

            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername,username);
            User user = mapper.selectOne(queryWrapper);
            if(user!=null){
                return R.error("已存在此用户！");
            }
            User registerUser=new User();
            registerUser.setUsername(username);
            registerUser.setPassword(password);
            registerUser.setNickname(username);
            mapper.insert(registerUser);
            return R.success(registerUser);
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }
}
